package com.rfid.a252robot.task;

import android.text.TextUtils;

import com.rfid.a252robot.event.BookQueryEvent;
import com.rfid.a252robot.event.OnShelfEvent;
import com.rfid.a252robot.net.BookLibApi;
import com.rfid.a252robot.net.BoxLibApi;
import com.rfid.a252robot.net.bean.BookInfoRespon;
import com.rfid.a252robot.net.bean.UploadBook;
import com.rfid.acs.bean.BookBean;
import com.rfid.common.log.LogUtils;
import com.rfid.db.bean.Book;
import com.rfid.db.bean.FailBook;
import com.rfid.db.bean.OperateInfo;
import com.rfid.manager.BookManager;
import com.rfid.manager.DBManager;
import com.rfid.manager.DoorBoxManager;
import com.rfid.manager.ReadTagManager;
import com.rfid.util.Util;
import com.shrfid.module_base.entity.TagEntity;
import com.spectre.generate.ConfigManager;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class OnShelfTask implements Runnable {

    int boxNum;
    boolean isCancel;
    public OnShelfTask(int boxNum) {
        this.boxNum = boxNum;
    }
    Executor mExecutor = Executors.newSingleThreadExecutor();

    @Override
    public void run() {
        int status = DoorBoxManager.INSTANCE.getLockOpenStatus(boxNum);
        while (status != 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            status = DoorBoxManager.INSTANCE.getLockOpenStatus(boxNum);
            System.out.println("getLockOpenStatus status = " + status);
            if (isCancel) {
                return;
            }
        }
        if (isCancel) {
            return;
        }
        EventBus.getDefault().post(new OnShelfEvent(boxNum,OnShelfEvent.STATUS_CHECKING));
        ReadTagManager.INSTANCE.selectAntenna(Util.getAntenna(boxNum));
        List<Book> books = DBManager.getBooks();
        List<Book> cbooks = DBManager.getBooks(boxNum);
        List<String> add = new ArrayList<>();
        int time = ConfigManager.INSTANCE.getGlobalConfig().getReadCount();
        while (time > 0) {
            LogUtils.v(String.format("倒数第%s次读取",time+""));
            List<TagEntity> tagEntities = ReadTagManager.INSTANCE.readTags();
            System.out.println("tagEntities = " + tagEntities);
            for (TagEntity tagEntity : tagEntities) {
                if (TextUtils.isEmpty(tagEntity.getBookNo())) {
                    continue;
                }
                for (Book book : cbooks) {
                    if (book.getBarcode().equals(tagEntity.getBookNo())) {
                        cbooks.remove(book);
                        break;
                    }
                }
                if (!add.contains(tagEntity.getBookNo())) {
                    boolean has = false;
                    for (Book book : books) {
                        if (book.getBarcode().equals(tagEntity.getBookNo())) {
                            has = true;
                            break;
                        }
                    }
                    if (!has) {
                        add.add(tagEntity.getBookNo());
                    }
                }
            }
            time--;
        }
        for (Book book : cbooks) {
            DBManager.deleteBook(book);
            sendDeleteInfoToServer(book);
        }
        doAddBook(add);
    }

    private void doAddBook(List<String> add) {
        for (String barcode : add) {
            Book book = new Book();
            book.setBarcode(barcode);
            book.setBoxNum(boxNum);
            book.setCanBorrow(true);
            DBManager.insertBook(book, OperateInfo.OPERATE_ADMIN_ONSHELF);
            BookManager.INSTANCE.searchBookWithBarcode(barcode)
                    .subscribe(new Consumer<BookBean>() {
                        @Override
                        public void accept(BookBean bookBean) throws Exception {
                            LogUtils.v(bookBean);
                            if (bookBean.isSuccess()) {
//                                Book book = new Book();
//                                book.setName(bookBean.getBookName());
//                                book.setBarcode(bookBean.getBookId());
//                                book.setBoxNum(boxNum);
//                                DBManager.insertBook(book, OperateInfo.OPERATE_ADMIN_ONSHELF);
                                Book book1 = DBManager.getBook(barcode);
                                book1.setName(bookBean.getBookName());
                                book1.setCanBorrow(true);
                                DBManager.updateBook(book1);
                                sendInfoToServer(book1);
                                queryIsbn(book1);
                                EventBus.getDefault().post(new BookQueryEvent(book1));
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            LogUtils.v("" + throwable.getMessage());
                            EventBus.getDefault().post(new BookQueryEvent(book));
                            FailBook fb = new FailBook();
                            fb.setBarcode(book.getBarcode());
                            fb.setBoxNum(book.getBoxNum());
                            fb.setBorrow(false);
                            DBManager.insertFailBook(fb);
                        }
                    });
        }
        EventBus.getDefault().post(new OnShelfEvent(boxNum,OnShelfEvent.STATUS_END));
    }

    private void queryIsbn(Book book) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BookInfoRespon info = BookLibApi.INSTANCE.getBookInfo(book.getBarcode());
                    List<BookInfoRespon.DataBeanX.DataBean.ItemsBean> itemsBeans = info.getData().getData().getItems();
                    if (itemsBeans != null && itemsBeans.size() > 0) {
                        List<BookInfoRespon.DataBeanX.DataBean.ItemsBean.IdentifiersBean> ids = itemsBeans.get(0).getIdentifiers();
                        if (ids != null&&ids.size() > 0) {
                            String isbn = ids.get(0).getValue();
                            book.setIsbn(isbn);
                            DBManager.updateBook(book);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void sendInfoToServer(Book book) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BoxLibApi.INSTANCE.uploadBook(book, UploadBook.TYPE_ADMIN);
                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtils.v(e.getMessage());
                }
            }
        });
    }

    private void sendDeleteInfoToServer(Book book) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BoxLibApi.INSTANCE.deleteBook(book, UploadBook.TYPE_ADMIN);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
